package com.springboot.cloud.sysadmin.organization.rest;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.utils.StringUtils;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.utils.EncryptUtils;
import com.springboot.cloud.sysadmin.organization.model.common.ResponseModel;
import com.springboot.cloud.sysadmin.organization.model.vo.CaptchaVO;
import com.springboot.cloud.sysadmin.organization.provider.AuthCodeProvider;
import com.springboot.cloud.sysadmin.organization.service.RedisService;
import com.springboot.cloud.sysadmin.organization.sms.SmsUtils;
import com.springboot.cloud.sysadmin.organization.until.RedisUtils;
import com.springboot.cloud.sysadmin.organization.entity.form.MobileForm;
import com.springboot.cloud.sysadmin.organization.entity.form.UserForm;
import com.springboot.cloud.sysadmin.organization.entity.po.User;
import com.springboot.cloud.sysadmin.organization.service.IUserService;
import com.springboot.cloud.sysadmin.organization.until.SmsTool;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 */
@RestController
@RequestMapping("/oauth")
@Api(tags = "注册")
@Slf4j

public class RegisterUserController {

    @Autowired
    private   IUserService userService;

    @Autowired
    private   AuthCodeProvider authCodeProvider;

    @Resource
    private RedisUtils redisUtils;

    /***
     * 注入redis模版
     */
    @Autowired
    private   RedisService redisService;

    private String tokenId = "TOKEN-USER-";

    @ApiOperation(value = "注册用户", notes = "新增一个用户")
    @ApiImplicitParam(name = "userForm", value = "新增用户form表单", required = true, dataType = "UserForm")
    @PostMapping(value = "/registerUser")
    public Result add(@Valid @RequestBody UserForm userForm) {
        log.debug("userForm:{}", userForm);
        if (userService.add(userForm.toPo(User.class))) {
            return Result.success("注册用户成功");
        } else {
            return Result.error("该账号或手机号已被注册");
        }
    }

    @ApiOperation(value = "手机号码注册用户", notes = "新增一个用户")
    @ApiImplicitParam(name = "mobileForm", value = "新增用户form表单", required = true, dataType = "MobileForm")
    @PostMapping("/mobile/registerUser")
    public Result register(@Valid @RequestBody MobileForm mobileForm) {
        String mobile = "+86" + mobileForm.toPo(User.class).getMobile();
        //首先比对验证码是否失效
        String redisauthcode = redisUtils.get(tokenId + mobile); //传入tonkenId返回redis中的value
        if (StrUtil.isBlank(redisauthcode)) {
            //如果未取到则过期验证码已失效
            return Result.error("验证码已过期");
        } else if (!"".equals(redisauthcode) && !EncryptUtils.getEncrypt(redisauthcode).equals(mobileForm.getSmscode())) {
            //验证码错误
            return Result.error("验证码错误");
        }
//        if(!EncryptUtils.getEncrypt(redisUtils.get(tokenId+mobile)).equals(mobileForm.getSmscode())){
//            return Result.error("手机验证码不正确");
//        }

//        log.debug("mobile:{}", uniqueId);
//        User user=new User();
//        user.setMobile(uniqueId);  m
        log.debug("mobile:{}", mobileForm);
        User user = new User();
        user.setMobile(mobileForm.toPo(User.class).getMobile());
        String pwd = "";
        if (user.getMobile().length() > 8) {
            pwd = user.getMobile().substring(user.getMobile().length() - 8, user.getMobile().length());
            log.debug("pwd3:" + pwd);
        } else {

            DecimalFormat zeroize = new DecimalFormat("0.000000");
            pwd = zeroize.format(Integer.valueOf(user.getMobile())).replace(".", "").substring(0, 8);
            log.debug("pwd4:" + pwd);
        }
        user.setPassword(pwd);
        String account = pwd + String.valueOf((int) ((Math.random() * 9 + 1) * 10));
        user.setUsername(account);
        if (userService.add(user)) {
            SimpleDateFormat sdf = new SimpleDateFormat();
            // 格式化时间
            sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
            // a为am/pm的标记
            Date date = new Date();// 获取当前时间
            redisUtils.set(tokenId + mobile, EncryptUtils.setEncrypt(sdf.format(date)));
//            redisUtils.set(mobile, EncryptUtils.setEncrypt(pwd,secret));
            return Result.success("注册账号成功,默认账号为[" + account + "],密码为[" + pwd + "]（请及时修改账号和重置密码！）", sdf.format(date));
        } else {
            return Result.error("该手机号已被注册");
        }
    }

    @ApiOperation(value = "手机号获取验证码", notes = "获取验证码")
    @ApiImplicitParam(name = "mobileForm", value = "获取手机短信form表单", required = true, dataType = "MobileForm")
    @PostMapping("/mobile/getSmsCode")
    public Result getSmsCode(@Valid @RequestBody MobileForm mobileForm) {
        String one = "13234567890abnopqrstcdefghijklmuvwxyz";
        String two = "13asdf234dfghzxcfew567890abnopqrstcdefghijklmuvwxyz";
        System.out.println("mobile:" + mobileForm.getMobile());
//        CaptchaVO captchaVO = new CaptchaVO();
//        captchaVO.setCaptchaVerification(mobileForm.getCaptchaVerification());
//        ResponseModel response = authCodeProvider.verify(captchaVO);
//        if(!response.getRepCode().equals("0000")){
//            return Result.error("验证码不正确");
//        }
        String mobile = "+86" + mobileForm.toPo(User.class).getMobile();
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        System.out.println("code:" + code);
        String smscode = SmsUtils.sendSms(code, new String[]{mobile}, new String[]{one, two});
        if (smscode.equals("false")) {
            return Result.error("手机短信发送失败");
        }
        System.out.println("mobile:" + mobile);
        redisUtils.set(tokenId + mobile, EncryptUtils.setEncrypt(code));
        redisService.expire(tokenId + mobile, 680);//调用reids工具类中存储方法设置超时时间
        return Result.success("手机短信发送成功");
    }

    @PostMapping("/sms/{mobile}")
    public String getSms(@PathVariable("mobile") String mobile) {
        return redisUtils.get(tokenId + "+86" + mobile);
    }

}

